package xyz.scootaloo.kami.cloud.handler

import io.vertx.ext.web.Router
import io.vertx.kotlin.coroutines.await
import xyz.scootaloo.kami.cloud.lang.getLogger
import xyz.scootaloo.kami.cloud.service.CacheService

/**
 * @author flutterdash@qq.com
 * @since 2022/4/11 18:09
 */
object HeartbeatHandler : RequestHandlerRegister {
    private val cacheService = CacheService()

    override val log by lazy { getLogger("ping-router") }
    override val mountPoint = "/ping"

    override fun register(router: Router) = router.run {
        get("/cache-put/:key/:value") { ctx ->
            val key = ctx.pathParam("key")
            val value = ctx.pathParam("value")
            cacheService.put(key, value)
            ctx.reply("OK")
        }

        get("/cache-get/:key") { ctx ->
            val key = ctx.pathParam("key")
            val value = cacheService.get(key).await()
            ctx.reply(value)
        }

        get("/cache-updateEx/:key/:time") { ctx ->
            val key = ctx.pathParam("key")
            val time = ctx.pathParam("time").toLong()
            cacheService.updateExpiryTime(key, time).await()
            ctx.reply("OK")
        }

        get("/*") { ctx ->
            ctx.reply("pong")
        }
    }
}